#include "CustomItemDelegate.h"
#include "QEvent"

CustomItemDelegate::CustomItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)  // 构造函数
{

}

void CustomItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    painter->save();

    // 判断是否选中
    if (option.state & QStyle::State_Selected) {
        painter->fillRect(option.rect, QColor(224, 224, 224));  // 设置选中时的深色背景（可以根据需要调整颜色）
    }

    // 获取数据
    QString title = index.data(Qt::DisplayRole).toString(); // 歌曲名字
    QString author = index.data(Qt::UserRole + 1).toString(); // 歌手名字
    QString duration = index.data(Qt::UserRole + 2).toString(); // 歌曲时长
    QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); // 图标

    // 设置图标的大小和位置
    QSize iconSize(50, 50);
    QRect iconRect(option.rect.adjusted(10, 5, 0, -5));  // 图片距离左边10像素，垂直居中
    iconRect.setSize(iconSize);

    // 设置文本的起始位置
    int textLeft = iconRect.right() + 10;

    // 绘制图标
    icon.paint(painter, iconRect, Qt::AlignLeft);

    // 计算文本区域
    int remainingWidth = option.rect.width() - iconRect.width() - 100;  // 剩余的宽度（减去图标和边距）
    int textWidth = remainingWidth / 3;  // 假设三个文本区域的宽度相等

    // 绘制歌曲名字
    QRect titleRect(textLeft, option.rect.top(), textWidth, option.rect.height());
    painter->drawText(titleRect, Qt::AlignVCenter | Qt::AlignCenter, title);

    // 绘制歌手名字
    QRect authorRect(titleRect.right(), option.rect.top(), textWidth, option.rect.height());
    painter->drawText(authorRect, Qt::AlignVCenter | Qt::AlignCenter, author);

    // 绘制歌曲时长
    QRect durationRect(authorRect.right(), option.rect.top(), remainingWidth - textWidth, option.rect.height());
    painter->drawText(durationRect, Qt::AlignVCenter | Qt::AlignCenter, duration);

    painter->restore();
}


QSize CustomItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QSize size = QStyledItemDelegate::sizeHint(option, index);
    size.setHeight(60);  // 设置行高为60像素
    return size;
}
